import 'dart:math';

import 'package:acgn_pioneer/plugin/dialog/index.dart';
import 'package:acgn_pioneer/providers/pop_slide_provider.dart';
import 'package:acgn_pioneer/utils/pop_util.dart';
import 'package:acgn_pioneer/widgets/reader/reader_base.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../public.dart';
import 'events/_index.dart';
import 'history.dart';

/// 阅读页组件(竖直方式)
class ReaderV extends StatefulWidget {
  ReaderV({Key key}) : super(key: key);

  @override
  ReaderVState createState() => new ReaderVState();
}

class ReaderVState extends ReaderBase<ReaderV> with TickerProviderStateMixin {
  double imageSwitchDistance = 300;
  double topPadding;
  bool isCanScroll = true; // 是否可以滚动

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((callback) {
      topPadding = MediaQuery.of(context).padding.top + 10;
    });

    scrollController.addListener(() {
      readerMainPage.doKeepPage();
      onUpdate();
    });
  }

  void _onRefresh() async {
    PopUtil.show(context, ReaderHistory(),
        transition: DialogTransition(duration: Duration(milliseconds: 400)),
        padding: EdgeInsets.only(top: topPadding));
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  Widget buildView() {
    var widget = buildContent();
    if (readModel.isPopNested) {
      return buildListen(widget);
    }

    return buildListen(RefreshConfig(
        child: SmartRefresher(
            enablePullDown: true,
            enablePullUp: true,
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: widget)));
  }

  buildContent() {
    return ListView.builder(
        physics: ClampingScrollPhysics(),
        shrinkWrap: true,
        controller: scrollController,
        itemCount: readModel.chapterImageList.length,
        itemBuilder: itemBuilder,
        scrollDirection: Axis.vertical);
  }

  Widget buildListen(Widget widget) {
    return NotificationListener(
        onNotification: (ScrollNotification notification) {
          if (notification is ScrollEndNotification) {
            readerPage.bus.fire(ReaderMoveEndEvent(scrollController.offset));
          }
          return true;
        },
        child: Listener(
            onPointerDown: onPointerDown,
            onPointerMove: onPointerUpdate,
            onPointerUp: onPointerEnd,
            child: widget));
  }

  /// 开始滚动
  void onPointerDown(PointerDownEvent pointerDownEvent) {
    start = scrollController.offset;
    touchX = pointerDownEvent.position.dx;
    touchY = pointerDownEvent.position.dy;
    setPopSlideStatus(false);
  }

  /// 结束滚动
  void onPointerEnd(PointerUpEvent pointerUpEvent) {
    if (scrollController.offset - start == 0 &&
        AreaUtil.isCenter(
            touchX, touchY, readModel.screenWidth, readModel.screenHeight)) {
      readerPage.bus.fire(ReaderCloseMenuEvent(true));
    }
    canclePopSlideStatus();
  }

  /// 滚动中
  void onUpdate() {
    var offset = scrollController.offset;
    var diff = offset - start;
    isNextDirection = diff > 0;
    updateCurrentChapter(offset);
    readerPage.bus.fire(ReaderCloseMenuEvent(false));
    readerPage.bus.fire(ReaderMoveEvent(offset));
  }

  // 如果有关联pop，则需取消相应设置
  void canclePopSlideStatus() {
    if (!readModel.isPopNested) {
      return;
    }
    isCanScroll = true;
    setPopSlideStatus(false);
  }

  // 设置关联pop滚动状态
  setPopSlideStatus(bool status) {
    if (!readModel.isPopNested) {
      return;
    }
    Provider.of<PopSlideProvider>(context, listen: false)
        .setSlideStauts(status);
  }

  // 如果有关联pop，则需设定相应设置
  void checkPopSlideStatus(PointerMoveEvent pointerMoveEvent) {
    if (!readModel.isPopNested) {
      return;
    }
    if (!isCanScroll) {
      scrollController.jumpTo(start);
    }

    if (start == 0 && pointerMoveEvent.delta.dy - start > 0) {
      isCanScroll = false;
      setPopSlideStatus(true);
    }
  }

  /// 拖拽中
  void onPointerUpdate(PointerMoveEvent pointerMoveEvent) async {
    checkPopSlideStatus(pointerMoveEvent);
  }

  // 图片展示大小调整
  void installResizeImg(ChapterImageModel sourceImage) {
    var width = sourceImage.originWidth;
    var height = sourceImage.originHeight;
    var rImg = width / height; // 图片宽高比
    var showWidth = min(width, readModel.screenWidth);
    var showHeight = (showWidth / rImg).floor().toDouble();

    sourceImage.originWidth = width;
    sourceImage.originHeight = height;
    sourceImage.showWidth = showWidth;
    sourceImage.showHeight = showHeight;
  }

  // 获取每个图片展示距离
  double getPerDistance(ChapterImageModel sourceImage) {
    double height = 0;
    sourceImage.slots.forEach((item) {
      height += item.height;
    });
    var imageHeight = sourceImage.showHeight != 0
        ? sourceImage.showHeight
        : readModel.screenHeight;
    return imageHeight + height;
  }
}
